import React from 'react'
import PageTitle from 'components/page-title/index.jsx'
import Pagination from 'util/pagination/index.jsx'
import {Link} from 'react-router-dom'
import MUtil from 'util/mm.jsx'
import Users from 'service/userList-service.jsx'

let _MUtil = new MUtil()
let _UserList = new Users()

class UserList extends React.Component{
  constructor(props) {
    super(props)
    this.state= {
      list: [],
      pageNum: 1,
      firstLoading: true
    }
  }
  componentDidMount(){
    this.getUserList()
  }
  
  getUserList(){
    _UserList.getUsers(this.state.pageNum).then( res=>{
      // console.log(res.list)
      this.setState(res, ()=>{
        this.state.firstLoading=false
      })
    }, err=>{
      this.setState({
        list: []
      });
      _MUtil.errorTips(err)
    } )
  }

  onPageNumChange(pageNum){
    this.setState({
      pageNum: pageNum
    }, ()=>{
      this.getUserList()
    })
  }

  render() {
    let listBody=this.state.list.map((item, index)=>{
                  return (
                    <tr key={index}>
                      <td>{item.id}</td>
                      <td>{item.username}</td>
                      <td>{item.phone}</td>
                      <td>{item.email}</td>
                      <td>{new Date(item.createTime).toLocaleString() }</td>
                    </tr>
                  )
                })
    let listError= (
      <tr>
        <td colSpan='5'>
          {this.state.firstLoading ? '正在加载数据...' : '没有找到相关数据~'}
        </td>
      </tr>
    )
    let tableBody= this.state.list.length >0 ? listBody : listError
    return (
      <div className="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
        <div className="row">
          <div className="col-md-12">
            <PageTitle title="用户列表页" />
          </div>
          <hr/>
        </div>
        <div className="row">
          <div className="col-md-12">
            <table className="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>用户名</th>
                  <th>phone</th>
                  <th>邮箱</th>
                  <th>creayeTime</th>
                </tr>
              </thead>
              <tbody>
                {tableBody}
              </tbody>
            </table>
          </div>         
        </div>
        <Pagination current={this.props.pageNum} total={this.state.total} onChange={(pageNum)=>this.onPageNumChange(pageNum)} />
      </div>
    ) 
  }

}

export default UserList